package com.hzcx.app.simplechat.chat.ui;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.chat.ChatUtil;
import com.hzcx.app.simplechat.chat.adapter.ChatMessageAdapter;
import com.hzcx.app.simplechat.chat.constant.ChatConstant;
import com.hzcx.app.simplechat.chat.interfaces.OnChatMessageListener;
import com.hzcx.app.simplechat.ui.group.bean.GroupInfoBean;
import com.hzcx.app.simplechat.ui.group.bean.MembersBean;
import com.hzcx.app.simplechat.ui.publicui.bean.HxUserInfoBean;
import com.hzcx.app.simplechat.util.log.LogUtils;
import com.hzcx.app.simplechat.util.toast.ToastUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 聊天列表list
 */
public class ChatMessageListView extends RelativeLayout {

    private static final int HANDLER_MESSAGE_REFRESH_LIST = 0;
    private static final int HANDLER_SCROLL = 1;

    @BindView(R.id.rv_msg)
    RecyclerView rvMsg;
    @BindView(R.id.swipe_refresh)
    SwipeRefreshLayout swipeRefresh;
    private Context context;

    private List<EMMessage> emMessageList;
    private ChatMessageAdapter messageAdapter;
    private EMConversation conversation;
    private String userName;
    private int chatType;

    protected boolean haveMoreData = true; // 是否还有更多消息

    public ChatMessageListView(Context context) {
        super(context);
        init(context);
    }

    public ChatMessageListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public ChatMessageListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.layout_chat_message_list, this);
        ButterKnife.bind(view);

        emMessageList = new ArrayList<>();
        messageAdapter = new ChatMessageAdapter(emMessageList);
        rvMsg.setLayoutManager(new LinearLayoutManager(context, RecyclerView.VERTICAL, false));
        rvMsg.setAdapter(messageAdapter);

        //底部布局弹出,聊天列表上滑
        rvMsg.addOnLayoutChangeListener((v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom) -> {
            if (bottom < oldBottom) {
                rvMsg.post(() -> {
                    if (messageAdapter.getItemCount() > 0) {
                        rvMsg.smoothScrollToPosition(messageAdapter.getItemCount() - 1);
                    }
                });
            }
        });
    }

    public void updateMembers(Map<String, MembersBean> userInfoGroupMap) {
        messageAdapter.updateMembers(userInfoGroupMap);
    }

    /**
     * 初始化消息列表数据
     *
     * @param userName
     * @param chatType
     */
    public void initEMConversation(String userName, int chatType) {
        this.userName = userName;
        this.chatType = chatType;

        conversation = EMClient.getInstance().chatManager().getConversation(userName, ChatUtil.getConversationType(chatType), true);
        conversation.markAllMessagesAsRead();

        emMessageList.clear();

        final List<EMMessage> msgs = conversation.getAllMessages();

        int msgCount = msgs != null ? msgs.size() : 0;
        if (msgCount < conversation.getAllMsgCount() && msgCount < ChatConstant.MESSAGE_PAGE_SIZE) {
            String msgId = null;
            if (msgs != null && msgs.size() > 0) {
                msgId = msgs.get(0).getMsgId();
            }
            emMessageList.addAll(conversation.loadMoreMsgFromDB(msgId, ChatConstant.MESSAGE_PAGE_SIZE - msgCount));
        }
        emMessageList.addAll(msgs);
        messageAdapter.notifyDataSetChanged();

        swipeRefresh.setOnRefreshListener(() -> {
            handler.postDelayed(() -> {
                swipeRefresh.setRefreshing(true);
                loadMoreMsg();
            }, 500);
        });

        rvMsg.scrollToPosition(emMessageList.size() - 1);
        rvMsg.postDelayed(new Runnable() {
            @Override
            public void run() {
                rvMsg.scrollToPosition(emMessageList.size() - 1);
            }
        },800);
    }


    /**
     * 从数据库加载历史消息
     */
    private void loadMoreMsg() {
        if (haveMoreData) {
            List<EMMessage> messages;
            try {
                messages = conversation.loadMoreMsgFromDB(conversation.getAllMessages().size() == 0 ? "" : conversation.getAllMessages().get(0).getMsgId(),
                        ChatConstant.MESSAGE_PAGE_SIZE);
            } catch (Exception e1) {
                swipeRefresh.setRefreshing(false);
                return;
            }
            if (messages.size() > 0) {
                messageAdapter.addData(0, messages);
                if (messages.size() != ChatConstant.MESSAGE_PAGE_SIZE) {
                    haveMoreData = false;
                }
            } else {
                haveMoreData = false;
            }
        } else {
            ToastUtils.show("没有更多消息了");
        }
        swipeRefresh.setRefreshing(false);

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == HANDLER_MESSAGE_REFRESH_LIST) {
                refreshListUiBySendMsg();
            } else if (msg.what == HANDLER_SCROLL) {
                rvMsg.scrollToPosition((Integer) msg.obj);
            }
        }
    };

    /**
     * 消息发送成功后，改变UI
     */
    private void refreshListUiBySendMsg() {
        List<EMMessage> var = conversation.getAllMessages();
        emMessageList.clear();
        emMessageList.addAll(var);
        conversation.markAllMessagesAsRead();
        messageAdapter.notifyDataSetChanged();
        rvMsg.scrollToPosition(messageAdapter.getItemCount()-1);
    }

    /**
     * 刷新list界面
     */
    public void refresh() {
        if (handler.hasMessages(HANDLER_MESSAGE_REFRESH_LIST)) {
            LogUtils.e("正在刷新列表，中断刷新");
            return;
        }
        Message msg = handler.obtainMessage(HANDLER_MESSAGE_REFRESH_LIST);
        handler.sendMessage(msg);
    }

    /**
     * 发送消息，添加
     */
    public void add() {
        try {
            rvMsg.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        EMMessage emMessage = emMessageList.get(emMessageList.size() - 1);
                        EMMessage emMessage1 = conversation.getAllMessages().get(conversation.getAllMessages().size() - 1);
                        if (!emMessage.equals(emMessage1)){
                            messageAdapter.addData(emMessage1);
                        }
                        rvMsg.scrollToPosition(messageAdapter.getItemCount() - 1);
                        rvMsg.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                rvMsg.scrollBy(100,900);
                            }
                        },600);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            refresh();
        }
    }

    /**
     * 手动添加消息
     *
     * @param message
     */
    public void add(EMMessage message) {
        messageAdapter.addData(message);
        rvMsg.scrollToPosition(messageAdapter.getItemCount() - 1);
    }


    /**
     * 搜索成功
     *
     * @param message
     */
    public void searchSuccess(EMMessage message) {

        // 从当前的数据源里面找匹配的消息ID
        for (int i = 0; i < emMessageList.size(); i++) {
            if (emMessageList.get(i).getMsgId().equals(message.getMsgId())) {
                Message msg = new Message();
                msg.what = HANDLER_SCROLL;
                msg.obj = i;
                handler.sendMessageDelayed(msg, 300);
                return;
            }
        }

        // 没有匹配的消息ID，去数据库找
        if (haveMoreData) {
            loadMoreMsg();
            searchSuccess(message);
        }

    }

    public RecyclerView getRvMsg() {
        return rvMsg;
    }

    public SwipeRefreshLayout getSwipeRefresh() {
        return swipeRefresh;
    }

    public ChatMessageAdapter getMessageAdapter() {
        return messageAdapter;
    }

    public List<EMMessage> getEmMessageList() {
        return emMessageList;
    }

    /**
     * 设置消息列表事件监听
     *
     * @param listener
     */
    public void setOnChatMessageListener(OnChatMessageListener listener) {
        messageAdapter.setOnChatMessageListener(listener);
    }

    public void setHxuserInfoBean(HxUserInfoBean hxuserInfoBean) {
        if (messageAdapter != null) {
            messageAdapter.setHxUserInfoBean(hxuserInfoBean);
        }
    }

    /**
     * 设置是否是选择更多模式
     *
     * @param isSelectMore
     */
    public void setIsSelectMore(boolean isSelectMore) {
        messageAdapter.setIsSelectMore(isSelectMore);
    }

    /**
     * 设置选中的列表
     */
    public void setCheckBoxList(List<Integer> list) {
        messageAdapter.setCheckBoxList(list);
    }
}
